<?php
/**
 * User: chenjin
 * Date: 2022/1/4
 * Time: 14:54
 */

namespace yi\web;

use Exception;
use Yi;

class Application extends \yi\base\Application
{
    protected function bootstrap()
    {
        $request = $this->getRequest();
        parent::bootstrap();
    }


    /**
     * @return \yi\web\Request
     * @throws Exception
     */
    public function getRequest()
    {
        //调用di中get
        return $this->get('request');
    }

    /**
     * @return \yi\web\UrlManager
     * @throws Exception
     */
    public function getUrlManager()
    {
        return $this->get('urlManager');
    }

    /**
     * @return \yi\web\UrlManager
     * @throws Exception
     */
    public function getView()
    {
        return $this->get('view');
    }

    public function getResponse()
    {
        return $this->get('response');
    }

    //配置文件中components若配置有如下键 class会被合并进配置文件中
    public function coreComponents()
    {
        return array_merge(parent::coreComponents(), [
            'request' => ['class' => 'yi\web\Request'],
            'response' => ['class' => 'yi\web\Response'],
        ]);
    }

    /**
     * @param Request $request
     */
    public function handleRequest($request)
    {
        list($route, $params) = $request->resolve();
        $result = $this->runAction($route, $params);

        if ($result instanceof Response) {
            return $result;
        }

        $response = $this->getResponse();
        if ($result !== null) {
            $response->data = $result;
        }
        return $response;
    }

}
